package com.mstore.dao;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import com.mstore.pojo.ExchangeLog;

public class ExchangeLogsDao extends SuperDao {

	public void addAddExlogs(ExchangeLog exchangeLog) {
		super.save(exchangeLog);
	}

	public List<Object> getAllExLogs(ExchangeLog exchangeLog) {
		String hql = "from ExchangeLog where eaId = ?";
		Object[] values = new Object[] { exchangeLog.getEaId() };
		return super.getObject(hql, values);
	}

	public List<Object> getExLogsByshop(ExchangeLog exchangeLog) {
		/*String sql = "from ExchangeLog where memberId="
				+ exchangeLog.getMemberId() + " and shopId = "
				+ exchangeLog.getShopId() + " order by createTime desc";*/
		
		StringBuilder sb=new StringBuilder();
		sb.append("from ExchangeLog where memberId=");
		sb.append(exchangeLog.getMemberId());
		sb.append(" and shopId = ");
		sb.append(exchangeLog.getShopId());
		sb.append(" order by createTime desc");
		
		List<Object> objcts = super.find(sb.toString());
		return objcts;
	}

	public List<Object> getExLogsByMember(ExchangeLog exchangeLog) {
		/*String sql = "from ExchangeLog where memberId="
				+ exchangeLog.getMemberId() + " order by createTime desc";
		List<Object> objects = super.find(sql);
		return objects;*/
		
		StringBuilder sb=new StringBuilder();
		sb.append("from ExchangeLog where memberId=");
		sb.append(exchangeLog.getMemberId());
		sb.append(" order by createTime desc");
		List<Object> objects = super.find(sb.toString());
		return objects;
	}

	public List<Object> getExLogsByEaAndMemberId(ExchangeLog exchangeLog) {
		String sql = "from ExchangeLog where memberId = "
				+ exchangeLog.getMemberId() + " and eaId = " + exchangeLog.getEaId()
				+ " order by createTime desc";
		List<Object> objects = super.find(sql);
		return objects;
	}

	/**
	 * 查询在某企业的兑换记录中的会员
	 */
	public List<Long> findMemberIdFromExchangeLog(Long eaId) {
		/*String sql = "SELECT DISTINCT member_id FROM b_exchangelog WHERE ea_id = "
				+ eaId;*/
		
		StringBuilder sb=new StringBuilder();
		sb.append("SELECT DISTINCT member_id FROM b_exchangelog WHERE ea_id = ");
		sb.append(eaId);
		Object object = super.executeSql(sb.toString());
		
		@SuppressWarnings("unchecked")
		List<Object> list = (ArrayList<Object>) object;
		List<Long> memberIds = new ArrayList<Long>();
		for (Object obj : list) {
			BigInteger bi = (BigInteger) obj;
			memberIds.add(bi.longValue());
		}
		return memberIds;
	}
	
	/**
	 * 获取会员兑换同一件商品的次数
	 * @param goodId
	 * @param memberId
	 * @return int
	 */
	public int getCountMemberExchangeLogByGoodId(Long goodId, Long memberId) {
		String sql = "select count(id) from ExchangeLog where goodId = ? and memberId = ?";
		List<Object> list = getObject(sql, new Object[] { goodId, memberId });
		if (list.isEmpty()) {
			return 0;
		}
		return ((Long)list.get(0)).intValue();
	}
	
}
